import pygame


class AnimatorComponent:
    def __init__(self, entity):
        self.Entity = entity
        self.IsPlayAnimation = False
        self.AnimationClipNextFlag = 0
        self.CurrentTime = 0
        self.TargetTime = 1
        self.TimeInternal = 3

    """播放一个动画，spriteParms为像要播放的精灵序列，time为持续时长，将做线性插值替换精灵实现动画效果"""
    """第一个参数是要播放的精灵名称"""
    """第二个参数是总共会花费的时间"""
    """第三个参数是是否在水平方向翻转"""

    def PlayAnim(self, spriteParms, time):
        if not self.IsPlayAnimation:
            self.SpriteParms = spriteParms
            self.IsPlayAnimation = True
            self.Entity.SetSprite(list(self.SpriteParms)[0])
            # print("当前显示的精灵为{0}".format(list(self.SpriteParms)[self.AnimationClipNextFlag]))
            self.AnimationClipNextFlag = 1
            self.CurrentTime = pygame.time.get_ticks()
            self.TimeInternal = time / list(self.SpriteParms).__len__()
            self.TargetTime = self.CurrentTime + self.TimeInternal
            self.Entity.image = pygame.transform.flip(self.Entity.image, self.Entity.FlipByX, False)
            # print("当前时间为{0},动画停止时间为{1}".format(self.CurrentTime, self.TargetTime))

    def Update(self):
        self.CurrentTime = pygame.time.get_ticks()
        if self.IsPlayAnimation:
            if self.AnimationClipNextFlag >= list(self.SpriteParms).__len__():
                self.AnimationClipNextFlag = 0
                self.IsPlayAnimation = False
                # print("动画播放完毕")
            if self.CurrentTime > self.TargetTime:
                self.Entity.SetSprite(list(self.SpriteParms)[self.AnimationClipNextFlag])
                self.CurrentTime = pygame.time.get_ticks()
                self.TargetTime = self.CurrentTime + self.TimeInternal
                # print("当前显示的精灵为{0}".format(list(self.SpriteParms)[self.AnimationClipNextFlag]))
                # print("当前时间为{0},动画停止时间为{1}".format(self.CurrentTime, self.TargetTime))
                self.AnimationClipNextFlag = self.AnimationClipNextFlag + 1
                self.Entity.image = pygame.transform.flip(self.Entity.image, self.Entity.FlipByX, False)
